<template>
	<view class="m-pay-modes">
		<u-action-sheet
			:show="show"
			@close="close"
			:title="title"
			:round="10"
		>
			<view class="p-b-md" v-if="actionShow">
				<!-- 获取支付状态 -->
				<view class="m-md flex-center">
					<u-loading-icon mode="circle" size="28rpx" text="正在支付" ></u-loading-icon>
				</view>
			</view>
			<view class="modes" v-if="modesShow">
				<!-- 支付选项 -->
				<u-radio-group 
					size="45rpx"
					iconSize="40rpx"
					labelSize="40rpx"
					placement="column" 
					v-model="paymode"
				>
					<u-radio
						:label="$t('m_pay_mode.action-mode-1')"
						name="1"
						activeColor="#2d8cf0"
						@change="radioChange"
						v-if="configInfo.alipay_open == 1"
					>
					</u-radio>
					<u-radio
						:label="$t('m_pay_mode.action-mode-2')"
						name="2"
						activeColor="#36b368"
						@change="radioChange"
						v-if="configInfo.wxpay_open == 1"
					>
					</u-radio>
					<u-radio
						:label="configInfo.money_company+'支付('+userInfo.money+')'"
						name="3"
						activeColor="#ffd426"
						@change="radioChange"
						v-if="moneyPay == 1 && userInfo"
					>
					</u-radio>
					<u-radio
						:label="'线下支付'"
						name="4"
						activeColor="#fa3534"
						@change="radioChange"
						v-if="configInfo.offpay_open == 1"
					>
					</u-radio>
				</u-radio-group>
				<view class="btns">
					<u-button shape="circle" :color="configInfo.mainColor" :loading="loading" :disabled="loading" loadingText=" " :text="$t('m_pay_mode.action-btn')" @click="pay" :style="{'color':configInfo.btnColor}"></u-button>
				</view>
			</view>
			
		</u-action-sheet>
	</view>
</template>

<script>
	import siteInfo from '@/siteinfo.js';
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		name:"pay-method",
		props: ['show','moneyPay'],
		data() {
			return {
				loading:false,
				paymode:'',
				orderNum:'',
				modesShow:true,
				actionShow:false,
				title:'',
				payLimitTimeData: {},
			};
		},
		computed: mapState({
			userInfo: state => state.user.userInfo,
			configInfo: state => state.config.configInfo,
		}),
		created(){
			this.init()
		},
		destroyed(){
			clearInterval(this.timer);
		},
		methods:{
			...mapActions(['getUserInfo']),
			init(){
				this.title = this.$t('m_pay_mode.action-title')
				this.orderNum 	= ''
				this.modesShow 	= true
				this.actionShow = false
				clearInterval(this.timer) // 销毁定时器
			},
			close(){
				this.init()
				this.$emit('close')
			},
			radioChange(n) {
				this.paymode = n;
				// console.log('radioChange', n);
			},
			
			pay(){
				// 点击确认支付按钮
				if(!this.paymode){
					this.$util.showToast(this.$t('m_pay_mode.action-title'))
					return false;
				}
				this.loading = true
				this.$emit('action',this.paymode)
			},
			
			async action(orderNum){
				this.orderNum = orderNum
				let params = {
					order_num	:	this.orderNum,
					is_weixin	:	false
				}
				if (this.$wechat.isWechat()) {
					// 微信浏览器
					params.is_weixin = 1;
				}
				// 若是线下支付则跳转
				if(this.paymode == 4){
					this.$util.go('pay/offpay?num='+orderNum)
					return;
				}
				let res = await this.$api.pay.snedPay(params)
				if(res.code == 200){
					let thos = this
					thos.modesShow = false
					thos.actionShow = true
					if(thos.paymode == 1){
						// 拼接支付完成跳转地址
						thos.openPay(res.data);
					}else{
						// 微信则需判断是否在微信浏览器内部
						if (thos.$wechat.isWechat()) {
							WeixinJSBridge.invoke(
							    'getBrandWCPayRequest',
							    res.data,
							    function(res2){
							        if(res2.err_msg == "get_brand_wcpay_request:ok" ){
										// 支付成功
							            // window.location.href = location.href;
							        } else if (res2.err_msg == 'get_brand_wcpay_request:fail') {
										thos.close()
										alert(res2.err_code+res2.err_desc+res2.err_msg);
							        }
								}
							);
						}else{
							// thos.openPay(res.data);
							// #ifdef H5
								if(uni.$u.os() == 'ios'){
									window.location.href = res.data;
								}else{
									window.open(res.data,'_blank');
								}
							// #endif
							// #ifdef APP-PLUS
								let url = res.data + '&is_close=1'  // 自动关闭跳转页面
								// app使用webview打开
								this.createWvAndLoadUrl(url);
							// #endif
						}
					}
					// 开启检测订单
					this.checkOrder()
				}else{
					this.close()
				}
			},
			
			// 建立webview
			createWvAndLoadUrl(url){
				const platform = uni.getSystemInfoSync().platform
				let height = 0;
				let statusbar = 0;
				uni.getSystemInfo({
					success(sysInfo) {
						statusbar = sysInfo.statusBarHeight;
						height	= sysInfo.windowHeight;
					}
				})
				const wv = plus.webview.create('',"pay-webview");
				switch(platform){
				  case 'android':
				    wv.loadURL(url,{'Referer':siteInfo.siteroot});
				    break;
				  case 'ios':
				    wv.loadURL(url,{'Referer':'develop.baicai.xiaocaiit.cn://'});
				    break;
				  default:
				    break;
				}
				wv.show();
				// var currentWebview = this.$mp.page.$getAppWebview(); //获取当前页面的webview对
				// currentWebview.append(wv); //一定要append到当前的页面里！！！才能跟随当前页面一起做动画，一起关闭
			},

			// 检测订单状态
			checkOrder(){
				this.title = '请尽快完成支付'
				console.log('开始检测订单支付状态：'+this.orderNum)
				if(!this.orderNum){
					return
				}
				let {
					orderNum
				} = this
				let thos = this
				let count = 1
				let maxCount = 10
				this.timer = setInterval(async () => {
					var res = await thos.$api.pay.getPayInfo({'order_num':orderNum});
					console.log('第'+count+'次检测支付订单:'+orderNum);
					// pay_limit_time 支付结束时间
					let {
						code,
						data:order
					} = res
					console.log(order.pay_limit_time)
					if(res.code == 200){
						if(order.order_state == 2){
							thos.$util.showToast(thos.$t('pay.pay-success'));
						}
						if(order.order_state == 3){
							thos.$util.showToast(thos.$t('pay.pay-success'),function(){
								thos.getUserInfo()
							})
							clearInterval(thos.timer)
							thos.close()
						}
					}
					if(count >= maxCount){
						clearInterval(thos.timer);
						thos.close()
					}
					count++
				}, 10000);
			},
			
			openPay(url){
				console.log(url)
				if(url){
					// // #ifdef H5
					// 	if(uni.$u.os() == 'ios'){
					// 		window.location.href = url;
					// 	}else{
					// 		window.open(url,'_blank');
					// 	}
					// // #endif
					// // #ifdef APP-PLUS
					// 	// app使用webview打开
					// 	this.createWvAndLoadUrl(url);
					// // #endif
					
					// #ifdef H5
						window.location.href = url 
						//  (url);
					// #endif
					// #ifdef APP-PLUS
						plus.runtime.openURL(url);
					// #endif
				}
			},
			
			onChange(e) {
			    this.payLimitTimeData = e
			}
		}
	}
</script>

<style lang="scss">
	.u-radio-group{
		justify-content: center;
		margin: 10px 0;
		align-items: center;
	}
	/deep/ .u-radio{
		margin: 10px;
		&__text{
			width: 200rpx!important;
		}
	}
	.btns{
		width: 320rpx;
		margin: 30rpx auto;
	}
.time {
    @include flex;
    align-items: center;

    &__custom {
         margin-top: 4px;
         width: 22px;
         height: 22px;
         background-color: $u-primary;
         border-radius: 4px;
         /* #ifndef APP-NVUE */
         display: flex;
         /* #endif */
         justify-content: center;
         align-items: center;
    
        &__item {
             color: #fff;
             font-size: 12px;
             text-align: center;
         }
    }
    
    &__doc {
         color: $u-primary;
         padding: 0px 4px;
     }
    
    &__item {
         color: #606266;
         font-size: 15px;
         margin-right: 4px;
     }
}
</style>